<?php
namespace app\index\controller;

use think\Controller;
use \Firebase\JWT\JWT;
/**
 * 公用基础控制器
 */
class BaseController extends Controller {

	protected function _initialize() {
		parent::_initialize();
		$cut_action = request()->action();
		
		if($cut_action == 'wechat_notify' || $cut_action == 'alipay_notify'){
			return true;
		}
		
		$jwt = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
		if ($jwt) {
			try {
				JWT::$leeway = 60;
				$decoded = JWT::decode($jwt, config('JWT_KEY'), array('HS256'));
				$arr = (array)$decoded;
				if ($arr['exp'] > time()) {
					$member = db('member')->where('password', $arr['data']->password)->find($arr['data']->id);
					if ($member) {
						session('user_id',$member['user_id']);
					}
				}
			} catch(\Exception $e) {
			}
		}
		if (!session('user_id')) {
			$this->redirect('index/index/login');
		} else {
			$this->assign('maction', request()->action());
		}
	}

	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	protected function get_code($config, $template_id, $mobile, $message) {
		$code = rand(1000, 9999);
		$data['mobile'] = $mobile;
		$data['code'] = $code;
		$data['message'] = $message;
		$data['add_time'] = now_time();
		include_once ('././extend/smsapi/smsDemo.php');
		$msg = sendSms($config, $template_id, $mobile, 'code', $code);
		if ($msg->Message == "OK") {
			$data['result'] = '发送成功';
			db('verify_code')->insert($data);
			$this->success('发送成功');
		} else {
			$err = $msg->Message;
			$data['result'] = '发送失败 - ' . $err;
			db('verify_code')->insert($data);
			$this->error('发送失败' . $err);
		}
	}	

}
